﻿using System;
using System.Collections.Generic;
using Vbyte.SharpOrm.Adapter;

namespace Vbyte.SharpOrm.SqlDb
{
    /// <summary>
    /// 实例表映射配置缓存
    /// </summary>
    public static class EntryTableCache
    {
        private static Dictionary<string, SqlTable> EntryTableDict = new Dictionary<string, SqlTable>();

        /// <summary>
        /// 获取实例相关的SQL表配置
        /// </summary>
        /// <param name="entry">实例类型样本</param>
        /// <returns>以对象方式表述的SQL表定义</returns>
        public static SqlTable GetTableCache(TableEntry entry)
        {
            return GetTableCache(entry, null);
        }

        /// <summary>
        /// 获取实例相关的SQL表配置
        /// </summary>
        /// <param name="entry">实例类型样本</param>
        /// <param name="builder">该实例上的SQL构建适配器实例</param>
        /// <returns>以对象方式表述的SQL表定义</returns>
        public static SqlTable GetTableCache(TableEntry entry, ISqlBuilderAdapter builder)
        {
            string key = entry.GetType().FullName;
            if (EntryTableDict.ContainsKey(key))
            {
                return EntryTableDict[key];
            }
            else
            {
                if (builder == null)
                {
                    using (AdoNetAdapter adp = new AdoNetAdapter(entry))
                    {
                        builder = adp.GetSqlBuilder();
                    }
                }
                SqlTable tab = entry.GetSqlTableDefine(builder);
                tab.InstanceType = entry.GetType();
                EntryTableDict.Add(key, tab);
                return tab;
            }
        }

        /// <summary>
        /// 清空缓存数据（缓存将自动创建）
        /// </summary>
        public static void ClearCache()
        {
            EntryTableDict.Clear();
        }

    }


}
